//
//  ZpOAuthController.m
//  WeiBo_OC
//
//  Created by MacBook Pro on 16/5/27.
//  Copyright © 2016年 MacBook Pro. All rights reserved.
//

#import "ZpOAuthController.h"
#import "ZpBarButtonItem.h"
#import "ZpUserAccount.h"
#import "ZpUserAccountViewModel.h"
@interface ZpOAuthController ()<UIWebViewDelegate>
@property (nonatomic, weak) UIWebView * webView;
@property (nonatomic, strong) ZpUserAccountViewModel *viewModel;
@end
@implementation ZpOAuthController

- (void)loadView{

    self.view = [[UIWebView alloc] init];
    self.webView = (UIWebView *)self.view;
}

- (void) viewDidLoad{
    [super viewDidLoad];
    self.viewModel = [ZpUserAccountViewModel shareUserAccountViewModel];
    [self setNavgationBar];
    [self.webView loadRequest: [self.viewModel loadWebView]];

    self.webView.delegate = self;
    [SVProgressHUD show];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [SVProgressHUD dismiss];
}

- (void)setNavgationBar{
    ZpBarButtonItem *leftItem = [ZpBarButtonItem barButtonItemWithImageName:nil andTitle:@"取消" andTarget:self andSelecor:@selector(closeOAuthController) andTitleNormalColor:[UIColor darkGrayColor] andTitleHightColor:[UIColor orangeColor]];
    
    ZpBarButtonItem *rightItem = [ZpBarButtonItem barButtonItemWithImageName:nil andTitle:@"自动填写" andTarget:self andSelecor:@selector(testAccount) andTitleNormalColor:[UIColor darkGrayColor] andTitleHightColor:[UIColor orangeColor]];
    
    self.navigationItem.leftBarButtonItem = leftItem;
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
//    NSString *urlString = request.URL.absoluteString;
//    NSString *successFlag = @"code=";
//    if ([urlString containsString:successFlag]) {
//        //截取字符串中的某个字符串
//        NSRange range = [urlString rangeOfString:successFlag];
//        NSString *code = [urlString substringFromIndex:range.location + range.length];
//        NSLog(@"%@", urlString);
//        NSLog(@"%@", code);
//        [self loadCode:code];
//        
//        return NO;
//    }
//    return YES;
    
    NSString *code = [self.viewModel needToSendHttpRequest:request];
    if (code) {

        [self.viewModel loadUserAccountWithCode:code andFinshed:^(NSError * error){
            if (error == nil) {
                [[NSNotificationCenter defaultCenter] postNotificationName:SwitchRootViewController object:nil];
                [SVProgressHUD dismiss];
                [self dismissViewControllerAnimated:NO completion:nil];
            }else{
                [SVProgressHUD showErrorWithStatus:@"授权失败"];
            }
        }];
      return NO;
    }
    return YES;
    
    
    
    
}

//- (void)loadUserInfo:(NSString *)code{
//    
//    [self.viewModel loadUserAccount:(BOOL)isSuccess];
//    NSDictionary *parameters = @{
//    @"client_id" : @"738009247",
//    @"client_secret": @"1bbba19aca17d9d89d2d354a8f0fa03b",
//    @"grant_type": @"authorization_code",
//    @"code":code,
//    @"redirect_uri":@"http://www.baidu.com"};
//    
//    __block NSDictionary *tokenDict;
//
//    NSString *urlString = @"https://api.weibo.com/oauth2/access_token";
//    [[ZpNetWorkTool shareNetWorkTool] sendHttpRequestWithMethod:POST andParameters:parameters andURLString:urlString andfinshed:^(NSData *data, NSError *error) {
//        
//    tokenDict = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//
//        NSString *urlString = @"https://api.weibo.com/2/users/show.json";
//        NSDictionary *dicts = @{
//            @"access_token" : tokenDict[@"access_token"],
//            @"uid" : tokenDict[@"uid"]
//        };
//        
//        [[ZpNetWorkTool shareNetWorkTool] sendHttpRequestWithMethod:GET andParameters:dicts andURLString:urlString andfinshed:^(NSData *data, NSError *error) {
//            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//            NSLog(@"%@", dict);
//            ZpUserAccount *userAccount = [ZpUserAccount userAccount:dict];
//            userAccount.access_token = tokenDict[@"access_token"];
//            userAccount.expires_in = [tokenDict[@"expires_in"] doubleValue];
//            NSLog(@"%@", userAccount);
//        }];
//
//    }];
    
//    NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/oauth2/access_token"];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//    request.HTTPMethod = @"POST";
//    NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
//    NSString *str = [NSString stringWithFormat:@"client_id=738009247&client_secret=1bbba19aca17d9d89d2d354a8f0fa03b&grant_type=authorization_code&code=%@&redirect_uri=http://www.baidu.com", code];
//    request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding];
//    
//    [[[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        [SVProgressHUD dismiss];
//        
//        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//        NSLog(@"%@",str);
//    }] resume];
    
//}


                                 
- (void)closeOAuthController{

    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)testAccount{
    //使用webView 执行js 字符串
    //js 动态注入
    NSString *jsString = @"document.getElementById('userId').value = 'leiggee@126.com', document.getElementById('passwd').value = 'onoyomg' ";
    [self.webView stringByEvaluatingJavaScriptFromString:jsString];

}


@end
